<template>
	<div
		:class="[
			'app-editor-container',
			'app-mob-radio-list',
			`app-mob-radio-list-${name}`,
		]"
	>
		<van-radio-group :disabled="disabled" v-model="curValue" @Change="onChange">
			<van-radio
				v-bind="$attrs"
				v-for="option in options"
				class="app-mob-radio-list__item"
				:key="option"
				:name="option.value"
				:disabled="option.disabled"
				@click="handleClick"
			>
				{{ option.text }}</van-radio
			>
		</van-radio-group>
	</div>
</template>
<script lang="ts" setup>
import { Ref } from 'vue';
import { IEvent } from '@/core';
import { radioListProps } from './radio-list';
interface EditorEmit {
	(name: 'editor-event', value: IEvent<string>): void;
}
const props = defineProps(radioListProps);
const emit = defineEmits<EditorEmit>();
const options: Ref<any[]> = ref([]);
const curValue = ref('');
onBeforeMount(() => {
	if (props.codeListTag && props.codeListType) {
		load();
	}
});

watch(
	() => props.value,
	(newVal: any, oldVal: any) => {
		if (newVal) {
			curValue.value = newVal;
		} else {
			curValue.value = '';
		}
	},
	{
		immediate: true,
	}
);

const load = async () => {
	try {
		const codeListResult = await App.getAppCodeListHelper().getCodeListItems(
			props.codeListTag as string,
			props.context,
			props.viewParams
		);
		if (codeListResult.ok) {
			options.value = codeListResult.data;
		}
	} catch (error) {
		console.error(error);
	}
};

const onChange = (value: any) => {
	if (!value) {
		return;
	}
	emit('editor-event', {
		name: `${props.name}`,
		action: 'valueChange',
		data: value,
	});
};

const handleClick = () => {
	emit('editor-event', {
		name: `${props.name}`,
		action: 'editorClick',
		data: curValue.value,
	});
};
</script>
